package com.dys.test12;

/**
 * @className: com.dys.test12.SynchronizedMethod
 * @description: com.dys.test12
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/08/19 下午9:59
 */
public class SynchronizedMethod implements Runnable {
    int ticketNum = 10;

    @Override
    public void run() {
        for (int i = 1; i <= 10000; i++) {
            buyTicket();
        }
    }

    /**
     * 同步方法: 锁住的是this
     */
    public synchronized void buyTicket() {
        if (ticketNum > 0) {
            System.out.println("我在" + Thread.currentThread().getName() + "，购买了从【深圳->贵阳】的第" + ticketNum-- + "张票");
        }
    }
}

class BuyTicketThread extends Thread {
    public BuyTicketThread(String name) {
        super(name);
    }

    // 一共10张票：
    static int ticketNum = 10;// 多个对象共享10张票

    @Override
    public void run() {
        // 每个窗口后面有100个人在抢票：
        for (int i = 1; i <= 100; i++) {
            buyTicket();
        }
    }

    /**
     * 锁住的  同步监视器： BuyTicketThread.class
     */
    public static synchronized void buyTicket() {
        // 对票数进行判断，票数大于零我们才抢票
        if (ticketNum > 0) {
            System.out.println("我在" + Thread.currentThread().getName() + "买到了从北京到哈尔滨的第" + ticketNum-- + "张车票");
        }
    }
}
